<template>
  <div
    id="db"
    style="height: calc(100vh - 36px); width: 100%; overflow: hidden"
  >
    <div style="height: 100%; width: 100%">
      <iframe
        id="drag"
        iframestyle="overflow-x:hidden;overflow-y:auto"
        allowfullscreen=""
        scrolling="yes"
        src="http://localhost:9300/#/drag"
        style="height: 100%; width: 100%; border: none"
        title="main"
      ></iframe>
    </div>
  </div>
</template>
<style></style>
<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { showAllColumns, showTables } from 'src/api/DatabaseApi';
import { renderTemplateContent } from 'src/api/render';
import { useTemplateStore } from 'stores/templateStore';
import { useYmlStore }      from 'stores/ymlStore';

const iframe = ref(null);
const sendMessage = (data: object) => {
  iframe.value?.contentWindow.postMessage(JSON.stringify(data), '*');
};

onMounted(() => {
  iframe.value = document.getElementById('drag');
  let url = location.href;
  const startIndex = url.indexOf('index.html#') + 'index.html#'.length;
  const result = url.substring(0, startIndex);
  iframe.value.src = result + '/drag';
  iframe.value.contentWindow.location.reload();

  window.addEventListener('message', async function (event) {
    let data = JSON.parse(event.data);
    console.log(data);
    if (data === 'table') {
      sendMessage({ data: tables, type: 'tables' });
      return;
    }
    if (data === 'template') {
      sendMessage({
        data: await useYmlStore().getYmlContentByName('mine-template'),
        type: 'template',
      });
      return;
    }
    if (!data.templateContent) {
      data.templateId;
      const res = await useTemplateStore().getTemplateContentById(
        data.templateId
      );
      data.templateContent = res.content;
      console.log(res.content);
    }
    sendMessage({
      data: {
        render: await renderTemplateContent(data.templateContent, data.data),
        content: data.templateContent,
      },
      type: 'render',
    });
  });
  initDbTree();
});
const dbTreeList = ref({} as { tables: object });
const dbTree = ref([
  {
    label: 'xiu-life',
    name: 'xiu-life',
    icon: 'storage',
    children: [
      {
        name: 'tables',
        label: 'tables',
        data: 'tables',
        icon: 'folder',
        children: [],
      },
    ],
  },
]);

let tables: never[] = [];
let mapper = {};
const initDbTree = async () => {
  await showTables().then(async (res) => {
    tables = res.results as [];
    mapper = {};
    tables.forEach((i, index) => {
      mapper[i.TABLE_NAME] = index;
      i.fields = [];
    });
    const columnList = (await showAllColumns()) as [];
    columnList.results?.forEach((i) => {
      tables[mapper[i.TABLE_NAME]].fields.push(i);
    });
    setTimeout(() => {
      sendMessage({ data: tables, type: 'tables' });
    }, 400);
  });
};
</script>
